package com.binance.mbxgateway.web.service.impl;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpStatusCodeException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.binance.assetservice.api.IProductApi;
import com.binance.assetservice.vo.request.product.GetProductItemRequest;
import com.binance.assetservice.vo.response.product.ProductItemResponse;
import com.binance.master.error.BusinessException;
import com.binance.master.error.GeneralCode;
import com.binance.mbxgateway.vo.request.klines.GetKlineRequest;
import com.binance.mbxgateway.vo.response.klines.GetKlinesResponse;
import com.binance.mbxgateway.web.service.IKlineService;
import com.binance.mbxgateway.web.service.IMatchboxRestService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class KlineServiceImpl extends BaseServiceImpl implements IKlineService {

    @Value("${matchbox.rest.root.url}")
    private String restUrl;

    @Autowired
    private IMatchboxRestService matchboxRestService;

    @Resource
    private IProductApi productApi;

    @Override
    public GetKlinesResponse getKline(GetKlineRequest request) throws Exception {
        String symbol = request.getSymbol();
        // To Do 根据prodcutService判断产品是否存在
        GetProductItemRequest body = new GetProductItemRequest();
        body.setSymbol(symbol);
        ProductItemResponse productResponse =
                this.getAPIRequestResponse(productApi.getProductItem(this.newAPIRequest(body)));
        if (productResponse == null || productResponse.getProductItems().isEmpty()) {
            throw new BusinessException(GeneralCode.PRODUCT_NOT_EXIST);
        }
        String json = null;
        try {
            json = this.matchboxRestService.fetchKlines(symbol, request.getInterval(), request.getStartTime(),
                    request.getEndTime(), request.getLimit());
        } catch (HttpStatusCodeException e) {
            String errJson = e.getResponseBodyAsString();
            log.error("getKline is error:{},{}", errJson, e);
            throw new BusinessException(errJson);
        } catch (Exception e) {
            log.error("getKline exception: {}", e);
            throw e;
        }
        JSONArray array = JSON.parseArray(json);
        GetKlinesResponse response = new GetKlinesResponse();
        array.forEach(arr -> {
            JSONArray data = (JSONArray) arr;
            GetKlinesResponse.KLineItem item = new GetKlinesResponse.KLineItem();
            item.setOpenTime(data.getLong(0));
            item.setOpen(data.getBigDecimal(1));
            item.setHigh(data.getBigDecimal(2));
            item.setLow(data.getBigDecimal(3));
            item.setClose(data.getBigDecimal(4));
            item.setVolume(data.getBigDecimal(5));
            item.setCloseTime(data.getLong(6));
            item.setQuoteAssetVolume(data.getBigDecimal(7));
            item.setNumberOfTrades(data.getLong(8));
            item.setTakerBuyBaseAssetVolume(data.getBigDecimal(9));
            item.setTakerBuyQuoteAssetVolume(data.getBigDecimal(10));
            item.setIgnore(data.getBigDecimal(11));
            response.getItems().add(item);
        });
        return response;
    }
}
